package app;


import java.util.ArrayList;
import java.util.Iterator;

import org.grlea.log.*;

import cluster.Duster;
import cluster.Observation;

import color.Color;

import proxml.*;
import processing.core.PApplet;
public class XMLParser {
	private static final SimpleLogger log = new SimpleLogger(app.XMLParser.class);
	ProgressListener listener;
	
	public XMLParser(ProgressListener listener){
		this.listener = listener;
	}
	
	public XMLParser(){
		
	}
	
	public static ArrayList<Duster<Color>> parseInTheMod(PApplet pa, String file){
		log.setDebugLevel(DebugLevel.L4_INFO);
		log.info("loading file: " + file + " ...");
		ArrayList<Duster<Color>> colors = new ArrayList<Duster<Color>>();
		XMLElement xml = null;
		try{
			XMLInOut xmlInOut = new XMLInOut(pa);
			xml = xmlInOut.loadElementFrom(file); 
			log.info("Successfully imported XML");    
		}catch(InvalidDocumentException ide){
			log.error("XML File does not exist");
		} 
		if(xml == null) return null;
		
		String palette = xml.getAttribute("freqDistribution");
		
		int index = 0;
		for (int i=0; i<palette.length(); i++){
			if (palette.charAt(i) == '[')
				index = i + 1;
			if (palette.charAt(i) == ']'){
				String s = palette.substring(index,i);
				log.debug("ColorString: " + s + " [0] = " +  s.split(",")[0]);
				int val = Integer.parseInt(s.split(",")[0]);
				log.debugObject("val" , val);
				
				colors.add(new Duster<Color>(new Color(val)));
			}
		}
		return colors;
	}
	public void writeClrXML(PApplet pa, ArrayList<Color> list, String fileName){
		XMLInOut out = new XMLInOut(pa);
		XMLElement root = new XMLElement("Colors");
		Iterator<Color> i = list.iterator();
		while(i.hasNext()) root.addChild(i.next().toXml());
		out.saveTo(root, fileName);
	}
	public void writeXML(PApplet pa, ArrayList<Observation<Color>> list, String fileName){
		XMLInOut out = new XMLInOut(pa);
		XMLElement root = new XMLElement("Colors");
		Iterator<Observation<Color>> i = list.iterator();
		int c = 0;
		while(i.hasNext()) {
			root.addChild(i.next().obs.toXml());
			c++;
			listener.progress("writeXML", (float)c / (float)list.size());
		}
		out.saveTo(root, fileName);
	}
	public static void writeXML(PApplet pa, Duster<Color> root, String fileName){
		XMLInOut out = new XMLInOut(pa);
		out.saveTo(writeXML(root), fileName);
	}
	
	private static XMLElement writeXML(Duster<Color> root){
		XMLElement xml;
		if(root.isRoot()) xml = new XMLElement("palette");
		else xml  = root.centroid.toXml();
		xml.addAttribute("id", root.getID());
		//xml.addAttribute("maxDist", root.maxDist);
		//xml.addAttribute("avgDist", root.avgDev);
		if(!root.isRoot()) xml.addAttribute("order", root.getParent().children.indexOf(root));
		else xml.addAttribute("order", 0);
		if(root.isLeaf()) return xml;
		Iterator<Duster<Color>> i = root.children.iterator();
		while(i.hasNext()) xml.addChild(writeXML(i.next()));
		return xml;
	}
	
	
}
